package lumis.portal.crypto;

import java.io.UnsupportedEncodingException;

import javax.crypto.SecretKey;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NoResultException;
import javax.persistence.Table;

import lumis.portal.manager.ManagerFactory;

import org.apache.commons.codec.binary.Base64;
import org.hibernate.annotations.GenericGenerator;

/**
 * Class used for storage of persistent data generated by 
 * {@link SymmetricCipher}.
 *
 * @version $Revision: 11180 $ $Date: 2009-12-04 18:13:02 -0200 (Fri, 04 Dec 2009) $
 * @since 5.5.0
 */
@Entity
@Table(name="lum_CrySymmetricCipher")
@GenericGenerator(name="portal-guid", strategy="lumis.portal.dao.hibernate.GuidGenerator")
class SymmetricCipherConfig
{
	@SuppressWarnings("unused")
	@Id @GeneratedValue(generator="portal-guid")
	private String id;
	
	private String cipherKey;
	private String iv;
	private String macKey;
	
	public SymmetricCipherConfig()
	{
	}
	
	SymmetricCipherConfig(SecretKey key, byte[] iv, SecretKey macKey)
	{
		try
		{
			this.cipherKey = new String(Base64.encodeBase64(key.getEncoded()), "UTF-8");
			this.iv = new String(Base64.encodeBase64(iv), "UTF-8");
			this.macKey = new String(Base64.encodeBase64(macKey.getEncoded()), "UTF-8");
		}
		catch (UnsupportedEncodingException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Returns the cipher's key.
	 * @return the cipher's key.
	 * @since 5.5.0
	 */
	byte[] getCipherKey()
	{
		return Base64.decodeBase64(cipherKey);
	}
	
	/**
	 * Returns the initialization vector.
	 * @return the initialization vector.
	 * @since 5.5.0
	 */
	byte[] getIv()
	{
		return Base64.decodeBase64(iv);
	}
	
	/**
	 * Returns the MAC's key.
	 * @return the MAC's key.
	 * @since 5.5.0
	 */
	byte[] getMacKey()
	{
		return Base64.decodeBase64(macKey);
	}
	
	/**
	 * Finds a {@link SymmetricCipherConfig} instance from persistence.
	 * @return the instance found.
	 * @throws NoResultException if no instance was found.
	 * @since 5.5.0
	 */
	static SymmetricCipherConfig find() throws NoResultException
	{
		return (SymmetricCipherConfig) ManagerFactory.getEntityManager().createQuery("select s from SymmetricCipherConfig s").getSingleResult();
	}
}